package com.maxverse.boot.web2image.core.controller;

import com.maxverse.boot.web2image.core.model.dto.ScreenshotRequest;
import com.maxverse.boot.web2image.core.model.vo.ApiResponse;
import com.maxverse.boot.web2image.core.model.vo.TaskResponse;
import com.maxverse.boot.web2image.core.service.ScreenshotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/v1/screenshot")
public class ScreenshotController {

    @Autowired
    private ScreenshotService screenshotService;

    @PostMapping
    public ApiResponse<TaskResponse> createTask(@Validated @RequestBody ScreenshotRequest request) {
        log.info("Received screenshot request for URL: {}", request.getUrl());
        TaskResponse response = screenshotService.createTask(request);
        return ApiResponse.success(response);
    }

    @GetMapping("/{taskId}/status")
    public ApiResponse<TaskResponse> getTaskStatus(@PathVariable String taskId) {
        log.info("Checking status for task: {}", taskId);
        TaskResponse response = screenshotService.getTaskStatus(taskId);
        return ApiResponse.success(response);
    }

    @GetMapping("/{taskId}/result")
    public ResponseEntity<byte[]> getTaskResult(@PathVariable String taskId) {
        log.info("Fetching result for task: {}", taskId);
        byte[] imageData = screenshotService.getTaskResult(taskId);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.setContentLength(imageData.length);
        
        return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
    }

    @GetMapping
    public ApiResponse<Page<TaskResponse>> getTasks(
            @RequestParam(required = false) String taskId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        return ApiResponse.success(screenshotService.getTasks(taskId, page, size));
    }

    @DeleteMapping("/{taskId}")
    public ApiResponse<Void> deleteTask(@PathVariable String taskId) {
        log.info("Deleting task: {}", taskId);
        screenshotService.deleteTask(taskId);
        return ApiResponse.success();
    }
} 